<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="购物车"
        left-text="返回"
        :right-text="'('+totalNum+')'"
        left-arrow
      />
    </header>
    <div class="content">
      <van-empty description="购物车空空如也" v-if="cartlist.length === 0"/>
      <van-swipe-cell
        v-else
        v-for="item of cartlist"
        :key="item.proid"
      >
        <van-card
          :price="item.price"
          :desc="item.desc"
          :num="item.num"
          :title="item.proname"
          :thumb="item.proimg"
        >
          <template #tags>
            <van-tag plain type="danger">{{ item.type }}</van-tag>
          </template>
          <template #footer>
            <van-button size="mini" @click="item.num += 1">+</van-button>
            <van-button size="mini" @click="item.num -= 1">-</van-button>
          </template>
        </van-card>
        <template #right>
          <van-button square text="删除" type="danger" class="delete-button" />
        </template>
      </van-swipe-cell>
      <van-submit-bar :price="totalPrice * 100" button-text="提交订单" @submit="onSubmit" />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Empty, SubmitBar, SwipeCell } from 'vant'

import axios from 'axios'
Vue.use(Empty)
Vue.use(SubmitBar)
Vue.use(SwipeCell)
export default {
  data () {
    return {
      cartlist: []
    }
  },
  computed: {
    totalNum () {
      return this.cartlist.reduce((sum, item) => {
        return sum + item.num
      }, 0)
    },
    totalPrice () {
      return this.cartlist.reduce((sum, item) => {
        return sum + item.num * item.price
      }, 0)
    }
  },
  mounted () {
    if (sessionStorage.getItem('loginstate') !== 'true') {
      this.$router.push('/login')
    }
    axios.get('http://nz1908.wudaxun.top/api/cart?userid=' + sessionStorage.getItem('userid')).then(res => {
      console.log('cart', res.data)
      this.cartlist = res.data.data
    })
  },
  methods: {
    onSubmit () {
      console.log('提交订单')
    }
  }
}
</script>

<style lang="scss">
.goods-card {
  margin: 0;
}

.delete-button {
  height: 100%;
}
</style>
